<template>
    <div class="home">
      <x-header :left-options="{showMore: false, showBack: false, backText:''}"><div @click="maskActive" class="default-canteen">{{defaultCanteen}}<span class="iconfont icon-Sy_baiJt"></span></div><a slot="right"><span class="iconfont icon-Ge_Xiaoxi" @click="show=!show"></span></a></x-header>

      <div v-show="isMask" @click="maskActive">
        <ul class="canteenlist" ref="abc">
          <li v-for="item in canteenlist" @click="selectCanteen(item)">{{item.text}}<span class="checkActive iconfont icon-Sy_xialagou" v-show="item.status"></span></li>
        </ul>
        <div class="weui-mask"></div>
      </div>

      <swiper loop auto :list="demo06_list" dots-position="center" class="home-swiper"></swiper>

      <!-- <x-dialog v-model="show" class="dialog-demo" :scroll="false">
        <p class="dialog-title">我的消息提醒</p>
        <div class="img-box">
          <ul @click="msgDet" v-show="isMsgOne">
            <li v-for="item in msgList" @click="det(item)">
                <div class="box-l iconfont" :class="item.icon"></div>
                <div class="box-r">
                  <p>{{item.title}}</p>
                  <p>{{item.info}}</p>
                </div>
            </li>
          </ul>
        </div>
        <p class="dialog-footer"><span class="iconfont icon-Sy_cha" @click="show=false"></span></p>
      </x-dialog> -->

    <section v-show="show" @touchmove.prevent class="msgdilog">
      <div class="weui-mask" style="z-index:1001" @click="show=!show" @touchmove.prevent></div>
      <div class="weui-dialog">
        <p class="dialog-title">我的消息提醒</p> 
        <div class="img-box">
        <ul @click="msgDet" v-show="isMsgOne">
          <li v-for="item in msgList" @click="det(item)">
            <div class="box-l iconfont" :class="item.icon"></div> 
            <div class="box-r">
            <p>{{item.title}}</p> 
            <p>{{item.info}}</p>
            </div>
          </li>
        </ul>
        </div> 
        <p class="dialog-footer" @click="show=!show"><span class="iconfont icon-Sy_cha"></span></p>
      </div>
    </section>


      <div :class="{touchBar:isFix}" style="width: 100%;overflow-x:scroll;-webkit-overflow-scrolling:touch;">
        <tab :style="{ width: widthComputed + 'px' }" :line-width=2 active-color='#ff4d4d' v-model="index">
          <tab-item class="vux-center" :selected="demo2 == item.name" v-for="(item, index) in goods" @click="demo2 = item.name" :key="index" @on-item-click="handler(item,index)">{{item.name}}</tab-item>
        </tab>
      </div>

      <div v-for="(item, index) in goods"  v-show="index==current">
        <div class="home-flex-box" v-for="(food,index) in item.foods">
          <div class="flex_l"><img :src="food.img" alt=""></div>
          <div class="flex_r">
              <p class="food-name">{{food.name}}</p>
              <p class="food-num">月售<span>{{food.sold}}份</span></p>
              <p class="food-price"><span class="price-icon">￥</span>{{food.price*0.01 | datadel}}</p>
              <Counter :food="food" ></Counter>
          </div>
        </div>
      </div>
      
      <Shopcart  :select-foods="selectFoods" v-show="isShop"></Shopcart>
      <Tabbar></Tabbar>
      <router-view></router-view>
    </div>

</template>

<script>
import Vue from 'vue'
import { Tab, TabItem, Swiper, SwiperItem, XHeader, Scroller, XDialog } from 'vux'
import Tabbar from '../common/Tabbar'
import Counter from '../common/Counter'
import Shopcart from '../common/Shopcart'


const baseList = [{
  url: 'javascript:',
  img: '/dist/static/img/bananer1.png'
}, {
  url: 'javascript:',
  img: '/dist/static/img/bananer3.png'
}]

const urlList = baseList.map((item, index) => ({
  url: '',
  img: item.img
}))

export default {
  components: {
    Tab, 
    TabItem, 
    Swiper, 
    XHeader,
    Scroller,
    SwiperItem,
    Shopcart,
    Tabbar,
    Counter,
    XDialog 
  },
  data () {
    return {
      isFix:false,
      isMsgOne:true,
      heightVal:null,
      demo2: '',
      index: 0,
      height:'',
      widthComputed:null,
      demo06_list: urlList,
      isCart:true,
      isMask:false,
      isShop:false,
      current:0,
      goods:[],
      shopFood:[],
      show: false,
      showNoScroll: false,
      showHideOnBlur: false,
      canteenlist:null,
      defaultCanteen:'',
      msgList:[
        {id:'',title:'订单消息',icon:'icon-Sy_DDXX',info:'暂无订单消息'},
        {id:'',title:'系统消息',icon:'icon-Sy_XTXX',info:'暂无系统消息'},
        {id:'',title:'互动消息',icon:'icon-Sy_HDXX',info:'暂无互动消息'},
      ]
    }
  },
  computed: {
    selectFoods() {
        let foods = [];
        let total =null;
        this.goods.forEach((good) => {
          good.foods.forEach((food) => {
            if (food.count) {
              foods.push(food);
            }
          });
        });
        foods.length>0?this.isShop=true:this.isShop=false;
        this.$store.commit('SELECTED_FOODS',foods);
        this.$store.commit('COM_TOTAL',foods);
        return foods;
    },
  },
  methods:{
    getUserId() {
      this.$http.get('/api/profile').then((res)=>{
        console.log(res.body);
        let id = res.body.data.id;
        localStorage.setItem('userId',JSON.stringify(id));
      });
    },
    scrollHander(){
      if(parseInt(window.scrollY)>180){
        this.isFix = true;
      }else{
        this.isFix = false;
      }
    },
    maskActive() {
      this.isMask = !this.isMask;
      this.height = this.$refs.abc.offsetHeight;
    },
    foodPull(id) {
      this.$http.get('/api/shops/'+id+'/foods').then((res) => {
          this.shopFood = res.body;
      });
      return this.shopFood
    },
    shopPull(id) {
      this.$http.get('/api/canteens/'+id+'/shops').then((res) => {
        //取窗口列表
        var shops = res.body.data;
        if(shops.length>0){
          if(shops.length>=3){
            this.widthComputed = shops.length*140;
          }else{
            this.widthComputed = 375;
          }
          this.demo2 = shops[0].name;
          this.$http.get('/api/shops/'+shops[0].id+'/foods').then((res) => {
            var shopFood = res.body;
            for(var i=0;i<shops.length;i++){
              if(i==0){
                this.current = 0;
                this.$store.commit('CURRENT_SHOP',0);
                this.$store.commit('CURRENT_NAME',shops[0].name);
                this.goods.push({"name":shops[i].name,"id":shops[i].id,"foods":shopFood});
                this.$store.commit('PULL_GOODS',this.goods);
              }else{
                this.goods.push({"name":shops[i].name,"id":shops[i].id,"foods":[]});
                this.$store.commit('PULL_GOODS',this.goods);
              }
            }
          });
        }else{
          this.goods = []; 
        }
      });
    },
    selectCanteen(item) {
      this.goods = [];
      this.canteenlist.forEach(function(key){
        key.status = 0;
      });
      item.status = 1;
      this.defaultCanteen = item.text;
      this.$store.commit('DEFAULT_CAMPOUS_NAME',item.text);
      this.shopPull(item.id);
    },
    handler(item,index) {
      this.current = index;
      this.$store.commit('CURRENT_SHOP',index);
      this.$store.commit('CURRENT_NAME',item.name);
      this.goods.forEach((good) => {
          good.foods.forEach((food) => {
            if (food.count) {
              food.count = 0;
            }
          });
      });
      this.$http.get('/api/shops/'+item.id+'/foods').then((res) => {
          var foodArr = res.body;
          for(var i=0;i<this.goods.length;i++){
            if(this.goods[i].id == item.id && this.goods[i].foods.length == 0){
              this.goods[i].foods = foodArr;
            }
          }
      });
    },
    getGoods() {
      this.$http.get('/api/delivery-addresses/default').then(function(res){
        this.getUserId();
        let campusId = res.body.data.campus_id;
        let defaultCampousId = this.$store.state.defaultCampousId;
        this.$http.get('/api/campuses/'+campusId+'/canteens').then(function(res){
            this.canteenlist = res.body;
            let id = this.canteenlist[0].id;
            //设置默认食堂
            this.defaultCanteen = this.canteenlist[0].text;
            this.$store.commit('DEFAULT_CAMPOUS_NAME',this.defaultCanteen);
            if(campusId != defaultCampousId){
              this.shopPull(id);
            }else{
              this.goods = this.$store.state.pullGoods;
              this.current = this.$store.state.currentShop;
              this.demo2 = this.$store.state.currentName;
              if(this.goods.length>=3){
                this.widthComputed = this.goods.length*140;
              }else{
                this.widthComputed = 375;
              }
            }
            this.canteenlist[0].status = 1;
        });
        this.$store.commit('DEFAULT_CAMPOUS_ID',campusId);
      });
    },
    det(item) {
      this.$http.get('/api/order/show/'+item.id).then((res)=>{
        this.order = res.body.data;
        this.isMsgOne = true;
        this.activeNo = true;
      });
    },
  },
  created() {
    var code = this.$route.query.code;
    var schoolId = this.$route.query.state;
    var redict = this.$route.query.to;
    if(code){
      this.$http.get('/api/wx/info',{params:{'code':code}}).then((res) => {
        //通过code获取openid
        let openid = res.body.data.openid;
        localStorage.setItem('openid',JSON.stringify(openid));
        this.$http.get('/api/wx/token',{params:{'openid':openid}}).then((res) => {
        //获取token验证用户是否注册
          localStorage.setItem('token',JSON.stringify(res.body.data));
          if(redict == 'take'){
            this.$router.push({path:'/dist/Menu'});
          }
          this.getGoods();
        }).catch(function(){
            this.$router.push({path:'/dist/Register',query: { school_id: schoolId}});
        });
        localStorage.setItem('userInfo',JSON.stringify(res.body.data));
      });
    }else if(!localStorage.getItem('token')){
       var schoolId = this.$route.query.school_id;
       var wxurl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx6e2c3819e77fc271&redirect_uri=http://www.un-sv.com/dist/&response_type=code&scope=snsapi_userinfo&state='+schoolId+'#wechat_redirect'; 
        window.location.href = wxurl;
    }

    this.getGoods();
  },
  mounted() {
    this.$nextTick(function(){
      window.addEventListener('scroll', this.scrollHander);
    });
  }
}

</script>

<style scoped lang="less">
@import '~vux/src/styles/close';
.vux-header{
  z-index:1001!important;
}
.home {
  text-align: center;
  padding-bottom:150px;
}
// .msgdilog .weui-mask{
//   margin-top:46px;
//   z-index:1000;
//   opacity: 1;
// }
.home .icon-Ge_Xiaoxi{
  font-size: 20px;
}
.home-flex-box{
  display: -webkit-flex;
  display: flex;
}
.flex_l{
  flex:4;
  -webkit-flex: 4;
  padding: 0.8rem 1.2rem;
}
.flex_l img{
  height: 10rem;
  width: 10rem;
  border-radius: 0.5rem;
}
.flex_r{
  flex:8;
  -webkit-flex:8;
  position: relative;
  padding-top: 20px;
}
.flex_r p{
  text-align: left;
  font-size:16px;
}
.flex_r:before{
  content: "";
  position: absolute;
  right: 0;
  bottom: 0;
  height: 1px;
  width: 100%;
  background-color: #bababa;
  transform: translateX(0.5);
  -webkit-transform: scaleY(0.5);
}
.food-price{
  position: absolute;
  left:0px;
  bottom:5px;
  font-size:24px!important;
  color:#ff4d4d;
}
.food-price span{
  font-size:14px;
}
.food-num{
  font-size: 14px;
}
.food-num span{
  color:#ff4d4d;
}
.home-swiper{
  margin-top: 46px;
}
.touchBar{ 
  position: fixed;  
  top: 46px;
  left:0;
  z-index: 100;
}
/* 首页食堂列表 */
.canteenlist{
  background-color: #fff;
  text-align: left;
  position: fixed;
  top: 46px;
  left: 0px;
  width: 100%;
  z-index: 1001;
}
.canteenlist li{
  position: relative;
  padding:10px 15px;
  font-size: 16px;
}
.canteenlist li:after{
  content: " ";
  position: absolute;
  right:0;
  left: 0;
  bottom: 0;
  background-color: #D9D9D9;
  width: 100%;
  height: 1px;
  -webkit-transform-origin: 0 0;
  transform-origin: 0 0;
  -webkit-transform: scaleY(0.5);
  transform: scaleY(0.5);
}
.default-canteen .iconfont{
  margin-left:0.6rem;
}
/* 弹出消息框样式 */
.dialog-demo {
  .dialog-title {
    line-height: 40px;
    color: #969696;
    font-size:20px;
  }
  .img-box {
    height: 300px;
    overflow: scroll;
    margin:0 1.5rem;
    border-top:1px solid #bababa;
  }
  .vux-close {
    margin-top: 8px;
    margin-bottom: 8px;
  }
}

.home .weui-dialog{
    position: fixed;
    z-index: 5000;
    width: 70%;
    max-width: 300px;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);
    background-color: #fff;
    border-radius: 8px;
    overflow: hidden;
    height:310px!important;
}
.home .dialog-title {
    line-height: 40px;
    color: #969696;
    font-size:20px;
}
.dialog-footer{
  position: absolute;
  bottom:0;
  left:0;
  width:100%;
  background-color:#ff4d4d;
  color:#fff;
}
.dialog-footer .iconfont {
  font-size:26px;
}
.img-box ul{
  padding-top:5px;
  border-top:1px solid #bababa;
}
.img-box{
  padding:0 16px 0 16px;
  li{
    display:flex;
    display:-webkit-flex;
    border-bottom:1px solid #bababa;
    .box-l{
      flex:1;
      margin-top: -5px;
      margin-bottom: -5px;
    }
    .box-r{
      padding-left:4px;
      flex:4;
      text-align:left;
      p:nth-child(1){
        padding-top:8px;
        font-size:16px;
        color:#3f3f3f;
      }
      p:nth-child(2){
        font-size:14px;
        color:#969696;
        width:200px;
        white-space:nowrap;
        overflow:hidden;
        text-overflow:ellipsis; 
      }
    }
  }
  .iconfont{
    font-size:46px;
  }
  .icon-Sy_DDXX{
    color:#ff4f2c;
  }
  .icon-Sy_HDXX{
    color:#ff4f2c;
  }
  .icon-Sy_XTXX{
    color:#2acb7b;
  }
}
/* 首页食堂选择下拉钩 */
.checkActive{
  position: absolute;
  right:1rem;
  top:50%;
  transform:translateY(-50%);
  -webkit-transform:translateY(-50%);
  color:#007aff;
  font-size:10px;
}
</style>
